<template>
  <div>
            <!-- 面包屑 -->
            <el-breadcrumb :separator-icon="ArrowRight">
              <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>账号列表</el-breadcrumb-item>
            </el-breadcrumb>

            <!-- 白色内容区域 -->
            <div class="page_content">
                  <!-- 1 -->
                  <div class="flex">
                    <div class="input-box">
                      <el-input
                        v-model="searchParams.query"
                        placeholder="搜索关键字"
                        class="input-with-select"
                      >
                        <template #append>
                          <el-button @click="searchList"><el-icon><Search /></el-icon></el-button>
                        </template>
                      </el-input>
                    </div>
                    <el-button type="primary" @click="addUser">新建用户</el-button>
                  </div>
                  <!-- 2表格 -->
                  <!-- el-table的data:要展示的数据数组
                        el-table-column：列
                        prop：每条数据的对应属性
                        label：列标题-->
                  <el-table :data="userList" style="width: 100%">
                    <el-table-column prop="username" label="姓名" width="180" />
                    <el-table-column prop="email" label="邮箱" width="180" />
                    <el-table-column prop="mobile" label="电话" />
                    <el-table-column prop="role_name" label="角色" />
                    <!-- mg_stat 当前用户的状态 -->
                    <!-- scope.row 相当于一条数据 -->
                    <el-table-column prop="mg_stat" label="状态">
                      <template #default="scope">
                        <el-switch
                          v-model="scope.row.mg_state"
                          @change="switchChange(scope.row)"
                        />
                      </template>
                    </el-table-column>

                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button type="primary" @click="editRow(scope.row)"
                          >编辑</el-button
                        >
                        <el-button type="danger" @click="deletetRow(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!-- 3分页 -->
                  <el-pagination
                    background
                    layout="prev, pager, sizes,next, jumper, ->, total"
                    v-model:current-page="searchParams.pagenum"
                    v-model:page-size="searchParams.pagesize"
                    :page-sizes="[2, 3, 5, 6]"
                    :total="total"
                    @size-change="searchList"
                    @current-change="searchList"
                  />
            </div>

            <!-- 新建用户的弹窗 -->
            <el-dialog v-model="dialogFormVisible" title="新建用户" width="500">
                  <!-- 表单 
                      username | 用户名称 | 不能为空 |
                    | password | 用户密码 | 不能为空 |
                    | email    | 邮箱     | 可以为空 |
                    | mobile   | 手机号   | 可以为空 |
                    -->
                  <!-- 如果在普通元素上，就是指向这个dome元素   el-form = userForm userForm包含rules-->
                  <el-form ref="userForm" :model="formData" :rules="rules">
                        <el-form-item label="用户名称" prop="username">
                          <el-input v-model="formData.username" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item label="用户密码" prop="password">
                          <el-input
                            type="password"
                            v-model="formData.password"
                            placeholder="请输入密码"
                          />
                        </el-form-item>
                        <!-- //prop绑定rules 里面的校验规则-->
                        <el-form-item label="邮箱" prop="email">
                          <el-input v-model="formData.email" placeholder="请输入用户邮箱" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="mobile">
                          <el-input v-model="formData.mobile" placeholder="请输入用户手机号" />
                        </el-form-item>
                  </el-form>
                  <template #footer>
                    <div class="flex">
                      <el-button>取消</el-button>
                      <!-- 把整个表单传到submitForm方法中 -->
                      <el-button type="primary" @click="submitForm(userForm)">确定</el-button>
                    </div>
                  </template>
            </el-dialog>
            <!-- 编辑用户的弹窗 -->
            <el-dialog v-model="dialogEFormVisible" title="编辑用户" width="500">
                  <!-- 表单 
                     | email  | 邮箱     | 可以为空                   |
                     | mobile | 手机号   | 可以为空                   |
                    -->
                  <el-form ref="userForm2" :model="formData2" :rules="rules2">
                        <!-- //prop绑定rules 里面的校验规则-->
                        <el-form-item label="邮箱" prop="email">
                             <el-input v-model="formData2.email" placeholder="请输入用户邮箱" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="mobile">
                             <el-input v-model="formData2.mobile" placeholder="请输入用户手机号" />
                        </el-form-item>
                  </el-form>
                  <template #footer>
                        <div class="flex">
                              <el-button>取消</el-button>
                              <!-- 把整个表单传到submitForm方法中 -->
                              <el-button type="primary" @click="submitEForm(userForm2)">确定</el-button>
                        </div>
                  </template>
            </el-dialog>

  </div>
</template>
    
<script>
import { toRefs, reactive, ref } from "vue";
import { userListApi, userAddApi, userChangeStateApi,userChangeInfoApi,userDeleteApi } from "@/util/request.js";
//请求用户数据库     用户增添（对话框）      用户改变状态       用户改变信息（编辑）（对话框）       用户删除信息（删除）（对话框）
export default {
  name: "users",
  setup() {
    const data = reactive({
      keyWord: "",
      searchParams: {
        query: "",
        pagesize: 5,
        pagenum: 1,
      },
      total: 0,
      userList: [],
      dialogFormVisible: false,//初始化时对话框关闭
      dialogEFormVisible: false,//初始化时对话框关闭
      formData: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formData2: {
        id:"",
        email: "",
        mobile: "",       
      },
     rules: {
        username: [{ required: true, message: "此项为必填", trigger: "blur" }],
        password: [{ required: true, message: "此项为必填", trigger: "blur" }],
        //prop 绑定了 email
        email: [
          {
            //非必填
            required: false,
            //正则表达式  很杂
            pattern:
              /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            // pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: "请填写正确邮箱",
            //失去焦后 才触发脚本
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: false,
            pattern: /^[1][3,4,5,6,7,8][0-9]{9}$/,
            message: "请填写正确手机号",
            trigger: "blur",
          },
        ],
      },
      rules2: {
        email: [
          {
            required: false,
            pattern:/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请填写正确邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: false,
            pattern: /^[1][3,4,5,6,7,8][0-9]{9}$/,
            message: "请填写正确手机号",
            trigger: "blur",
          },
        ],
      },
    });

    const searchList = () => {
          //分页查询参数data.searchParams
          //定义处理方式  ：拿到res后怎么处理这个值
          userListApi(data.searchParams).then((res) => {
                if (res.data) {
                      console.log("用户数据", res);
                      //<el-table :data="userList" 绑定了table 中的list
                      data.userList = res.data.users;
                      data.total = res.data.total;
                }
          });
    };
    const addUser = () => {
      data.dialogFormVisible = true;//打开对话框
    };
    //新建用户弹窗的提交
    const submitForm = (formEl) => {
          /* 1校验表单 */
          //validate el-form 自带的方法  表单校验 如邮箱格式 ，手机号码长度应该11
          //validate 根据 el-form 设置的rules 对表单元素进行校验
          formEl.validate((res) => {
                if (!res) {
                  //如果校验不通过，那不执行任何操作
                  return;
                }
          /* 2表单校验成功后，发出Api请求 */
          userAddApi(data.formData).then((res) => {
                //判断用户添加接口是否有数据响应
                if (res.data) {
                    //如果有响应数据，说明数据库已经添加成功
                     data.dialogFormVisible = false;//隐藏弹窗
                     data.formData = {
                      username: "",
                      password: "",
                      email: "",
                      mobile: "",
                    };//清空form
                    searchList();//重新更新列表
                  }
                });
          });
    };
    //编辑用户弹窗的提交
    const submitEForm=(formEl)=>{
            formEl.validate((res) => {
                  if (!res) {
                      return;
                  }
            userChangeInfoApi(data.formData2).then(res=>{
                  if(res.data){
                    data.dialogEFormVisible=false;
                    searchList()
                  }
              })
            })
    }
    //状态更改
    const switchChange = (row) => {
            console.log("操作的那条数据", row);
            userChangeStateApi(row).then((res) => {
              if (res.data) {
                searchList();
              }
            });
    };
    //用户编辑
    const editRow = (row) => {
            const {email,mobile,id}=row;//扩展语法          
            console.log("编辑的那条数据", row);
            //展示编辑表单
            data.dialogEFormVisible=true;
            data.formData2.email=email;
            data.formData2.mobile=mobile;
            data.formData2.id=id;
    };
    //用户删除
    const deletetRow=(row)=>{
          console.log("删除的那条数据", row);
          userDeleteApi(row).then(res=>{ 
            if(res.meta.status){
              searchList();
            }
          })
    }
    //方法初始化  一进入界面就调用
    searchList();
    
    const userForm = ref();
    const userForm2 = ref();
    return {
      //扩展函数  data = {name:"lihongke"}  ...data
      // a= b   c=a   改变c的值 b的会变  a= ...b c=a  修改c的值 b不会变化
      ...toRefs(data),
      searchList,
      addUser,
      submitForm,
      submitEForm,
      userForm,
      userForm2,
      switchChange,
      editRow,
      deletetRow,
    };
  },
};
</script>
    
<style scoped>
.input-box {
  width: 200px;
  margin-right: 15px;
}
</style>